package com.cnit1818.generator;

import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.sql.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 * User: MaYong
 * Date: 12-11-20
 * Time: 上午11:01
 * To change this template use File | Settings | File Templates.
 */
@Component
public class CreateEntityFile {
    @Value("#{configProperties.ftlDir}")
    private String ftlDir;
    @Value("#{configProperties.entitySrcDir}")
    private String entitySrcDir;
    @Value("#{configProperties.entity}")
    private String entityDir;

    /**
     * 返回第一个字母大写的字符串
     *
     * @param tableName
     * @return
     */
    private String getTableName(String tableName) {
        tableName = tableName.toLowerCase();
        String tmp = "";
        boolean b = false;
        for (int i = 0; i < tableName.length(); i++) {
            String k = tableName.substring(i, i + 1);
            if (k.equals("_")) {
                b = true;
                continue;
            } else {
                if (b) {
                    tmp = tmp + k.toUpperCase();
                } else {
                    tmp = tmp + k.toLowerCase();
                }
                b = false;
            }
        }
        tmp = tmp.substring(0, 1).toUpperCase() + tmp.substring(1, tmp.length());
        return tmp;
    }

    private String getPackageStr(String string) {
        string = string.replace('.', '/');
        string = "/" + string;
        return string;
    }

    private String getFieldName(String tableName) {
        tableName = tableName.toLowerCase();
        String tmp = "";
        boolean b = false;
        for (int i = 0; i < tableName.length(); i++) {
            String k = tableName.substring(i, i + 1);
            if (k.equals("_")) {
                b = true;
                continue;
            } else {
                if (b) {
                    tmp = tmp + k.toUpperCase();
                } else {
                    tmp = tmp + k.toLowerCase();
                }
                b = false;
            }
        }
        tmp = tmp.substring(0, 1).toLowerCase() + tmp.substring(1, tmp.length());
        return tmp;
    }

    public void createEntity(String templateDir, Hashtable<String, String> translateTable, DataSource dataSource,
                             String tableName)
            throws IOException, SQLException, TemplateException {
        File file = new File(entitySrcDir + getPackageStr(entityDir) + "/" + getTableName(tableName) + ".java");
        if (file.exists()) {
            System.out.println("文件存在 ---- 跳过Entity ---");
            return;
        }
        System.out.println("文件不存在 -- 生成Entity ---");
        OracleTable mysqlTable = new OracleTable();
//        MysqlTable mysqlTable = new MysqlTable();
        Configuration cfg = new Configuration();
        cfg.setDirectoryForTemplateLoading(new File(ftlDir));
        cfg.setObjectWrapper(new DefaultObjectWrapper());
        Template temp = cfg.getTemplate("entity.ftl");
        Connection connection = dataSource.getConnection();
        String sql = "select * from " + tableName + " where 2=3";
        Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery(sql);
        ResultSetMetaData rsMetaData = rs.getMetaData();
        //拿到每个字段的注释值
        DatabaseMetaData databaseMetaData = connection.getMetaData();
//        ResultSet databaseResultSet = databaseMetaData.getColumns(null, databaseMetaData.getUserName().toUpperCase(), tableName.toUpperCase(), null);
        ResultSet databaseResultSet = databaseMetaData.getColumns(null, null, tableName.toUpperCase(), null);
        List remarkList = new ArrayList();
        while (databaseResultSet.next()) {
            if (databaseResultSet.getString("REMARKS") == null) {
                remarkList.add("");
            } else {
                remarkList.add(databaseResultSet.getString("REMARKS"));
            }
        }
        //拿到每个字段的注释值end

        int count = rsMetaData.getColumnCount();
        Map<String, Object> root = new HashMap<String, Object>();
        root.put("class", getTableName(tableName));
        root.put("package", entityDir);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        SimpleDateFormat sdf_time = new SimpleDateFormat("HH:mm:ss");
        String date = sdf.format(new Date());
        root.put("date", date);
        String time = sdf_time.format(new Date());
        root.put("time", time);
        Collection<Map<String, String>> properties = new HashSet<Map<String, String>>();
        root.put("properties", properties);
        for (int i = 1; i <= count; i++) {
            Map map = new HashMap();
            String type = rsMetaData.getColumnTypeName(i);
            String typeName = translateTable.get(type);
            if (typeName == null || typeName.equals("")) {
                typeName = type;
            }
            map.put("name", getTableName(rsMetaData.getColumnName(i)));
            map.put("type", typeName);
            map.put("memo", remarkList.get(i - 1));
//            map.put("memo", " //" );
            properties.add(map);
        }
        Writer o = new FileWriter(file);
        temp.process(root, o);
        o.flush();
        databaseResultSet.close();
        rs.close();
        statement.close();
        connection.close();
    }
}
